// pages/welcome/index/index.js

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //是否显示授权弹窗
    getPhoneNumberChange: false
  },

  /**
   * 解析手机号码/unionID
   */
  parsePhone(encryptedData, iv) {
    wx.showLoading({
      title: '拼命加载中...',
    });
    wx.request({
      url: app.globalData.url + 'c=home&m=getPhoneNumber',
      data: {
        'encryptedData': encryptedData,
        'iv': iv,
        'code': wx.getStorageSync('code')
      },
      success: (res) => {
        res = res.data;
        if (res.status == 200) {
          //保存unionID到本地
          // var phone = res.data.purePhoneNumber;
          var union_id = res.data.unionId;
          wx.setStorageSync('union_id', union_id);
          //判断unionID是否注册
          wx.request({
            url: app.globalData.url + 'c=user&m=isRegister',
            data: {
              union_id: union_id
            },
            success: res => {
              wx.hideLoading();
              res = res.data;
              if (res.status == 200) {
                if (res.data.is_register == 0) {
                  //未注册
                  wx.redirectTo({
                    url: '/pages/guidanceStudy/visitor_index/index'
                  });
                } else {
                  //已注册
                  wx.setStorageSync('user_id', res.data.user_id);
                  app.globalData.userId = res.data.user_id;
                  // wx.redirectTo({
                  //   url: '/pages/guidanceStudy/index/index'
                  // });
                  wx.redirectTo({
                    url: '/pages/student/index/index'
                  });
                }
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none'
                });
              }
            }
          })
        } else {
          wx.showToast({
            title: '获取个人信息失败，请重试',
            icon: 'none'
          })
          this.setData({
            getPhoneNumberChange: true
          })
        }
      }
    })
  },


  //手机号码授权回调
  getPhoneNumber(e) {
    if (e.detail.iv && e.detail.encryptedData) {
      this.setData({
        'getPhoneNumberChange': false
      });
      this.parsePhone(e.detail.encryptedData, e.detail.iv);
    } else {
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      })
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    this.checkLoad(options);
    //如果user_id存在
    var user_id = wx.getStorageSync('user_id')
    if (user_id) {
      //判断user_id是否有效
      wx.request({
        url: app.globalData.url + 'c=user&m=getUserInfo&user_id=' + user_id,
        success: res => {
          res = res.data;
          if (res.data.id) {
            //用户存在，直接进入用户首页
            wx.setStorageSync('user', res.data);
            // wx.redirectTo({
            //   url: '/pages/guidanceStudy/index/index'
            // });
            wx.redirectTo({
              url: '/pages/student/index/index'
            });
            //存储是否是第一次登录信息
            wx.setStorageSync('is_first', res.data.is_first);
        
          } else {
            //用户不存在，移除本地user_id
            wx.removeStorageSync('user_id');
            wx.removeStorageSync('user');
            // this.havaPhone();
            this.havaUnionID();
          }
        }
      })
    } else {
      // this.havaPhone();
      this.havaUnionID();
    }
  },

  //检查是否是扫码进入
  checkLoad(options) {
    if (JSON.stringify(options) !== '{}') {
      app.globalData.enterpriseId = options.enterpriseId;
      app.globalData.refId = options.refId;
      app.globalData.idNumber = options.idNumber;
      wx.redirectTo({
        url: '/pages/welcome/applydesc/applydesc'
      });
    }
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      let arrPara = scene.split("&")
      let arr = [];
      for (let i = 0; i < arrPara.length; i++) {
        arr = arrPara[i].split("=");
        if (arr[0] == 'enterpriseId') {
          app.globalData.enterpriseId = arr[1];
        }
        if (arr[0] == 'refId') {
          app.globalData.refId = arr[1];
        }
        if (arr[0] == 'idNumber') {
          app.globalData.idNumber = arr[1];
        }
      }
      wx.redirectTo({
        url: '/pages/welcome/applydesc/applydesc'
      });
    }
  },


  havaPhone() {
    if (wx.getStorageSync('phone')) { 
      wx.redirectTo({
        url: '/pages/guidanceStudy/visitor_index/index'
      });
    }
    //如果不存在手机号码，要求授权手机号码
    wx.login({
      success: res => {
        wx.setStorageSync('code', res.code);
        this.setData({
          getPhoneNumberChange: true
        });
      }
    })
  },

  havaUnionID() {
    if (wx.getStorageSync('union_id')) {
      wx.redirectTo({
        url: '/pages/guidanceStudy/visitor_index/index'
      });
    }else{
      //如果不存在union_id，要求授权union_id
      this.getSetting();
      wx.login({
        success: res => {
          wx.setStorageSync('code', res.code);
          this.setData({
            getPhoneNumberChange: true
          });
        }
      })
    }
  },

  //是否授权
  getSetting() {
    wx.getSetting({
      success: res => {
        //没授权过
        if (!res.authSetting['scope.userInfo']) {
          this.setData({
            getPhoneNumberChange: true
          })
        } else {
          //授权过
          if (!(wx.getStorageSync('wx_name') && wx.getStorageSync('wx_head'))) {
            wx.getUserInfo({
              success: res => {
                wx.setStorageSync('wx_name', res.userInfo.nickName);
                wx.setStorageSync('wx_head', res.userInfo.avatarUrl);
              }
            });
          }
        }
      }
    })
  },

  //授权获取个人头像和昵称
  getUserInfo(e) {
    if (e.detail.userInfo) {
      wx.setStorageSync('wx_head', e.detail.userInfo.avatarUrl);
      wx.setStorageSync('wx_name', e.detail.userInfo.nickName);
      this.parsePhone(e.detail.encryptedData,e.detail.iv);
      wx.showToast({
        title: '获取个人信息成功',
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '个人信息授权失败',
        icon: 'none'
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})